﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using WmWebSystem.Models;
using WmWebSystem.Service;

namespace WmWebSystem.DbHelper
{
     public static class SliderHelper
    {
        public static void CreateNewToSliders(Slider model)
        {
            WmDb mydb = new WmDb();

            try
            {
                mydb.Sliders.Add(model);
                mydb.SaveChanges();
                //将记录写入日志
                string p1 = "Add new to Sliders, The SliderTitle:" + model.Title;
                WriteLog.WriteSysLog(p1);
            }
            catch (FieldAccessException ex)
            {
                //失败，进行回滚操作  记录异常
                File.Delete(model.DelPath);
                WriteLog.WriteSysLog(ex.ToString());
            }

        }

        public static void DeleteFromSliders(int id)
        {
            WmDb mydb = new WmDb();
            var sli = mydb.Sliders.Find(id);

            //删除项目
            try
            {
                //删除物理文件
                System.IO.File.Delete(sli.ImgUrl);

                mydb.Sliders.Remove(sli);
                mydb.SaveChanges();
                //将记录写入日志
                string p1 = "Delete a slider from Sliders, where SliderId:" + id;
                WriteLog.WriteSysLog(p1);
            }
            catch (FieldAccessException ex)
            {
                //失败，进行回滚操作  记录异常
                WriteLog.WriteSysLog(ex.ToString());
            }

        }

        //public  static string CreateNewFolderToSlider()
        //{
        //    string path = AppDomain.CurrentDomain.BaseDirectory + "Content\\Sliders";

        //    if (!Directory.Exists(path))
        //    {
        //        Directory.CreateDirectory(path);
        //        return path;
        //    }
        //    else
        //    {
        //        return path;
        //    }
        //}

        public static IEnumerable<Slider> AllSlider() 
        {
            WmDb mydb = new WmDb();
            var slider = from s in mydb.Sliders
                         orderby s.AddTime descending
                         select s;
            return slider;
        }
    }
}
